/*package com.zbdx.controller;

import com.zbdx.domain.User;
import com.zbdx.service.UserService;
import com.zbdx.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/shopping/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = new User(0, username, password);
        try {
            if (userService.register(user)) {
                resp.sendRedirect("login.jsp");
            } else {
                req.setAttribute("error", "Registration failed");
                req.getRequestDispatcher("register.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Registration failed");
        }
    }
}*/


package com.zbdx.controller;

import com.zbdx.domain.User;
import com.zbdx.service.UserService;
import com.zbdx.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/shopping/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        try {
            // 检查用户名是否已存在
            if (userService.userExists(username)) {
                req.setAttribute("error", "Username already exists");
                req.getRequestDispatcher("register.jsp").forward(req, resp);
            } else {
                // 如果不存在，则尝试注册
                User user = new User(0, username, password);
                if (userService.register(user)) {
                    resp.sendRedirect("login.jsp");
                } else {
                    req.setAttribute("error", "Registration failed");
                    req.getRequestDispatcher("register.jsp").forward(req, resp);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Registration failed");
        }
    }
}
